const moment = require('moment')
const md5 = require('md5');
const jwt = require('jwt-simple')
// 防破解加密key
const KEY = 'for(let i=0;i<10000;i++){console.log("iloveyou")}'
module.exports = {
    getNowTime:()=>{
        return moment().format('YYYY-MM-DD HH:mm:ss')
    },
    md5:(password)=>{
        return md5(password + KEY)
    },
    // 加密  {adminName:'atguigu'}
    encode:(payload,exp=60*60*24)=>{
        // 加入过期时间
        payload.exp = Date.now()/1000 + exp// {adminName:'atguigu',exp:xxxx}
        console.log('payload',payload)
        return jwt.encode(payload,KEY)
    },
    // 解密
    decode:(token)=>{
        // 1. 成功
        // 2. 失败
        return new Promise((resolve,reject)=>{
            // 解密失败会报错，所以用try-catch处理
            try{
                let payload = jwt.decode(token,KEY)
                resolve(payload)
            }catch(e){
                reject(e.message)
            }
        })
    }
}